package com.xingmang.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: hss
 * @create 2023/6/27
 */
public class AuthFilter implements GlobalFilter, Ordered {
    //排除的链接
    @Value("${gateway.excludedUrls}")//这里填写自己不需要拦截的请求路径
    private List<String> excludedUrls;

    //过滤器
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求路径
        String path = exchange.getRequest().getURI().getPath();
        //判断是否需要拦截
        if (excludedUrls.contains(path)){
            return chain.filter(exchange);//放行
        }
        //校验token数据
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");//自己的字段
        if(!StringUtils.isEmpty(token)){
            token = token.replaceAll("Bearer", "");
        }

        //2、使用工具类，判断token是否有效
//        boolean verifyToken = JwtUtils.verifyToken(token);//这里需要自己配置判断token的手段
//        //3、如果token失效，返回状态码401，拦截
//        if(!verifyToken) {
//            Map<String, Object> responseData = new HashMap<>();
//            responseData.put("errCode", 401);
//            responseData.put("errMessage", "用户未登录");
//            return responseError(exchange.getResponse(),responseData);
//        }
        return chain.filter(exchange);
    }

    private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData) {
        // 将信息转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try {
            data = objectMapper.writeValueAsBytes(responseData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 输出错误信息到页面
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 设置过滤器的执行顺序
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

}
